//
//  SNMapView.m
//  project
//
//  Created by 圆圆陈 on 2017/12/11.
//  Copyright © 2017年 黄建华. All rights reserved.
//

#import "SNMapView.h"
#import <MapKit/MapKit.h>
#import "HMAnnotation.h"
#import "HMAnnotationView.h"
#import "LocationTranformTool.h"
#import <QuartzCore/QuartzCore.h>
#import "TrackModel.h"
#import "AnimationView.h"
@interface SNMapView ()<MKMapViewDelegate,CLLocationManagerDelegate,UIAlertViewDelegate>
//位置管理者
@property (nonatomic, strong) CLLocationManager *localManager;
//地图
@property (nonatomic, strong) MKMapView *mapView;

@property(nonatomic,strong)CLGeocoder *geocoder;
//存放用户位置的数组
@property (nonatomic, strong)NSMutableArray *locationMutableArray;
@property(nonatomic,strong)NSMutableArray *annoArr;
@property(nonatomic,assign)float minLat;
@property(nonatomic,assign)float maxLat;
@property(nonatomic,assign)float minLon;
@property(nonatomic,assign)float maxLon;
@property(nonatomic,assign)MKCoordinateRegion region;
@property(nonatomic,assign)NSInteger distance;
@property(nonatomic,strong)HMAnnotation *startAnno;
@property(nonatomic,strong)HMAnnotation *endAnno;
@property(nonatomic,strong)UIView *topBackView;
@property(nonatomic,strong)UILabel *detailLabel;
@property(nonatomic,strong)UIButton *backBtn;
@property(nonatomic,strong)UIButton *shareBtn;
@property(nonatomic,strong)UIButton *setBtn;
@property(nonatomic,strong)UIButton *startBtn;
@property(nonatomic,strong)UIImageView *gpsImageView;
@property(nonatomic,strong)UIImageView *signImageView;
@property(nonatomic,strong)UIView *bottomView;
@property(nonatomic,strong)UIButton *locationBtn;
@property(nonatomic,strong)UILabel *distanceLabel;
@property(nonatomic,strong)UILabel *calLabel;
@property(nonatomic,strong)UILabel *speedLabel;
@property(nonatomic,strong)UILabel *paceLabel;
@property(nonatomic,strong)UILabel *timeLabel;
@property(nonatomic,strong)TrackModel *trackModel;
@property(nonatomic,strong)NSMutableArray  *speedArr;
@property(nonatomic,strong)NSTimer *timer;
@property(nonatomic,assign)NSInteger totalTime;
@property(nonatomic,strong)UIImage *image;
@property(nonatomic,strong)UIView *backView;
@property(nonatomic,strong)NSMutableArray *allDataArray; //1经度 2纬度 3海拔 4时间
@end

@implementation SNMapView
-(instancetype)initWithFrame:(CGRect)frame{
    if (self=[super initWithFrame:frame]) {
        //创建存放位置的数组
        _distance = 0;
        _totalTime = 0;
        _allDataArray = [[NSMutableArray alloc] init];
        _locationMutableArray = [[NSMutableArray alloc] init];
        _annoArr = [[NSMutableArray alloc] init];
        _trackModel = [[TrackModel alloc]init];
        _speedArr = [NSMutableArray array];
        //全屏显示地图并设置地图的代理
        _mapView = [SingletonMapView sharedInstance];
        _mapView.delegate = self;
        //_mapView.showsCompass = NO;
        [self addSubview:_mapView];
        [self addTopView];
        [self addMapViewItem];
        [self addBottomView];
        _image = [UIImage new];
        _localManager = [[CLLocationManager alloc]init];
        //设置代理
        _localManager.delegate = self;
        //设置定位的精度
        [_localManager setDesiredAccuracy:kCLLocationAccuracyBest];
        //位置信息更新最小距离
        _localManager.distanceFilter = 20;
        if ([UIDevice currentDevice].systemVersion.floatValue >= 9.0) {
            _localManager.allowsBackgroundLocationUpdates = YES;
        }
        if ([_localManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
            [_localManager requestAlwaysAuthorization];
        }
        self.geocoder = [[CLGeocoder alloc] init];
        
        [_localManager startUpdatingLocation];
    }
    return self;
}
-(void)addTopView{
    _topBackView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, HHHWIDTH, 60)];
    _topBackView.backgroundColor = [UIColor blackColor];
    _topBackView.alpha = 0.5;
    [self addSubview:_topBackView];
    
    _backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_backBtn setImageNormal:@"返回"];
    _backBtn.frame = CGRectMake(10, 10, 40, 40);
    [_backBtn addTouchUpTarget:self action:@selector(backBtnClick:)];
    [_topBackView addSubview:_backBtn];
    UIImage *image = [[UIImage alloc]init];
    NSArray *sunArr = @[@"100"];
    NSArray *cloudArr = @[@"101",@"102",@"103",@"101",@"101",@"201",@"202",@"203",@"204"];
    NSArray *snowArr = @[@"400",@"401",@"402",@"403",@"404",@"405",@"406",@"407",];
    NSArray *overcastArr = @[@"104",@"200",@"205",@"206",@"207",@"208",@"210",@"500",@"501",@"502",@"503",@"504",@"507",@"508"];
    NSArray *rainArr = @[@"209",@"211",@"212",@"213",@"300",@"301",@"302",@"304",@"305",@"306",@"307",@"308",@"309",@"310",@"311",@"312",@"313"];
    NSArray *nonArr = @[@"900",@"901",@"902"];
    image = UIImageNamed(@"无");
    if ([sunArr containsObject:KK_WeatherModel.weatherCode]) {
        image = UIImageNamed(@"晴天");
    }else if ([cloudArr containsObject:KK_WeatherModel.weatherCode]){
        image = UIImageNamed(@"多云");
    }else if ([snowArr containsObject:KK_WeatherModel.weatherCode]){
        image = UIImageNamed(@"雪");
    }else if ([overcastArr containsObject:KK_WeatherModel.weatherCode]){
        image = UIImageNamed(@"6阴天");
    }else if ([rainArr containsObject:KK_WeatherModel.weatherCode]){
        image = UIImageNamed(@"雨");
    }else if([nonArr containsObject:KK_WeatherModel.weatherCode]){
        
    }
    _weatherView = [[UIImageView alloc]initWithFrame:CGRectMake(_backBtn.right+10, _backBtn.centerY -14, 28, 28)];
    [_weatherView setImage:image];
    [_topBackView addSubview:_weatherView];
    
    _temperatureLabel = [[UILabel alloc]initWithFrame:CGRectMake(_weatherView.right+10, 20, 90, 20)];
    _temperatureLabel.textAlignment = NSTextAlignmentLeft;
    if (SN_USER.temperatureSet) {
         _temperatureLabel.text = [NSString stringWithFormat:@"%d-%d℉",(int)(KK_WeatherModel.minTem.integerValue *1.8+32),(int)(KK_WeatherModel.maxTem.integerValue *1.8+32)];
    }else{
         _temperatureLabel.text = [NSString stringWithFormat:@"%@-%@℃",KK_WeatherModel.minTem,KK_WeatherModel.maxTem];
    }
   
    _temperatureLabel.font = SNFONT(FitFont(21));
    _temperatureLabel.textColor = [UIColor whiteColor];
    [_topBackView addSubview:_temperatureLabel];
    
//    _detailLabel = [[UILabel alloc]initWithFrame:CGRectMake(_weatherView.right+10, _temperatureLabel.bottom, 60, 20)];
//    _detailLabel.text = @"空气质量：一般";
//    _detailLabel.hidden = !SN_USER.boolShoWeatherInfo;
//    _detailLabel.textAlignment = NSTextAlignmentLeft;
//    _detailLabel.textColor = [UIColor whiteColor];
//    _detailLabel.font = [UIFont systemFontOfSize:8];
//    [_topBackView addSubview: _detailLabel];
    
    _setBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_setBtn setImageNormal:@"设置白"];
    _setBtn.frame = CGRectMake(HHHWIDTH-10-50*2-10, 5, 50, 50);
    [_setBtn addTouchUpTarget:self action:@selector(setBtnClick:)];
    [_topBackView addSubview:_setBtn];
    
    _shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_shareBtn setImageNormal:@"shareButton"];
    _shareBtn.frame = CGRectMake(HHHWIDTH-10-50, 5, 50, 50);
    [_shareBtn addTouchUpTarget:self action:@selector(shareBtnClick:)];
    [_topBackView addSubview:_shareBtn];
}
-(void)addMapViewItem{
    _gpsImageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, _topBackView.bottom+10, 80, 28)];
    _gpsImageView.layer.cornerRadius =8;
    _gpsImageView.clipsToBounds = YES;
    [_gpsImageView setImage:[UIImage imageWithColor:UIColorHEX(0xD3292D)]];
   
    [self addSubview:_gpsImageView];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, _gpsImageView.width/2, 28)];
    label.text = @"GPS";
    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentCenter;
    [_gpsImageView addSubview:label];
    
    _signImageView = [[UIImageView alloc]initWithFrame:CGRectMake(_gpsImageView.width/2, 0, 30, 28)];
    [_signImageView setImage:UIImageNamed(@"信号4")];
    [_gpsImageView addSubview:_signImageView];
    
    _locationBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    _locationBtn.frame = CGRectMake(10, HHHHEIGHT*2/3, 50, 50);
    [_locationBtn setImageNormal:@"定位"];
    _locationBtn.hidden = YES;
    [_locationBtn addTouchUpTarget:self action:@selector(locationBtnClick:)];
    [self addSubview:_locationBtn];
    
    _backView = [[UIView alloc]initWithFrame:CGRectMake(HHHWIDTH/3, HHHHEIGHT*2/3, HHHWIDTH/3+10, HHHWIDTH/3+10)];
    _backView.backgroundColor = UIColorRGBA(208, 207, 198, 0.5);
    _backView.center = CGPointMake(HHHWIDTH/2, HHHHEIGHT*2/3+HHHWIDTH/6);
    _backView.layer.cornerRadius =(HHHWIDTH/3+10)/2;
    _backView.clipsToBounds = YES;
    UIView *view1 = [[UIView alloc]initWithFrame:CGRectMake(4, 4, HHHWIDTH/3+2, HHHWIDTH/3+2)];
    view1.backgroundColor = UIColorRGBA(144, 146, 141, 0.5);
    view1.layer.cornerRadius =(HHHWIDTH/3+2)/2;
    view1.clipsToBounds = YES;
    [_backView addSubview:view1];
    [self addSubview:_backView];
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
    animation.duration = 2.0;
    animation.repeatCount = HUGE_VALF;
    animation.autoreverses = YES;
    animation.beginTime = CACurrentMediaTime();
    animation.timingFunction =[CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionEaseInEaseOut];
    animation.removedOnCompletion = NO;
    animation.fillMode = kCAFillModeForwards;
    animation.fromValue = [NSNumber numberWithFloat:1.0];
    animation.toValue = [NSNumber numberWithFloat:1.1];
    [_backView.layer addAnimation:animation forKey:@"scale-layer"];

    _startBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_startBtn setImageNormal:@"ready"];
    _startBtn.frame = CGRectMake(HHHWIDTH/3, HHHHEIGHT*2/3, HHHWIDTH/3, HHHWIDTH/3);
    _startBtn.layer.cornerRadius = HHHWIDTH/6;
    _startBtn.clipsToBounds = YES;
    [_startBtn setBackgroundColor:SNCOLORBLACK];
    [_startBtn addTouchUpTarget:self action:@selector(startBtnClick:)];
    [self addSubview:_startBtn];
}
-(void)addBottomView{
    _bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, HHHHEIGHT-FitH(140), HHHWIDTH, FitH(140))];
    _bottomView.backgroundColor = [UIColor blackColor];
    _bottomView.alpha = 0.5;
    _bottomView.hidden = YES;
    [self addSubview:_bottomView];
    
    UILabel *finishLabel = [[UILabel alloc]initWithFrame:CGRectMake(5,FitH(20), HHHWIDTH/5-5, FitH(30))];
    finishLabel.text = SN_Text(@"已完成");
    finishLabel.textAlignment = NSTextAlignmentLeft;
    finishLabel.textColor = [UIColor whiteColor];
    finishLabel.font = SNFONT(FitFont(16));
    [_bottomView addSubview:finishLabel];
    finishLabel.size = [self returnTrueSizeOfLabel:finishLabel];
   
    
    _distanceLabel = [[UILabel alloc]initWithFrame:CGRectMake(finishLabel.right+2,FitH(20), HHHWIDTH*1/5, FitH(30))];
    _distanceLabel.text = SN_USER.isMetricSystem?@"0.00mile":@"0.00km";
    _distanceLabel.textAlignment = NSTextAlignmentCenter;
    _distanceLabel.textColor = [UIColor whiteColor];
    _distanceLabel.font = SNFONTMIN(FitFont(16));
    [_bottomView addSubview:_distanceLabel];
    
    UILabel *cal = [[UILabel alloc]initWithFrame:CGRectMake(HHHWIDTH*7/12,FitH(20), HHHWIDTH/4, FitH(30))];
    cal.text = SN_Text(@"卡路里燃烧");
    cal.textAlignment = NSTextAlignmentRight;
    cal.textColor = [UIColor whiteColor];
    cal.font = SNFONT(FitFont(16));
    [_bottomView addSubview:cal];
    CGSize size = [self returnTrueSizeOfLabel:cal];
    cal.frame = CGRectMake(HHHWIDTH*3/4-size.width-2+10, FitH(20), size.width, size.height);
    
    _calLabel =[[UILabel alloc]initWithFrame:CGRectMake(HHHWIDTH*3/4+10,FitH(20), HHHWIDTH/4-10, FitH(30))];
    _calLabel.text = @"0.00kcal";
    _calLabel.textAlignment = NSTextAlignmentLeft;
    _calLabel.textColor = [UIColor whiteColor];
    _calLabel.font = SNFONTMIN(FitFont(16));
    [_bottomView addSubview:_calLabel];

    UILabel *speedT = [[UILabel alloc]initWithFrame:CGRectMake(5, finishLabel.bottom, HHHWIDTH/6-5, FitH(30))];
    speedT.textAlignment = NSTextAlignmentLeft;
    speedT.textColor = [UIColor whiteColor];
    speedT.text = SN_Text(@"时速");
    speedT.font = SNFONT(FitFont(16));
    [_bottomView addSubview:speedT];
    speedT.size = [self returnTrueSizeOfLabel:speedT];
    
    _speedLabel = [[UILabel alloc]initWithFrame:CGRectMake(speedT.right+2,finishLabel.bottom, HHHWIDTH / 2 -speedT.width-10, FitH(30))];
    _speedLabel.text = @"";
    _speedLabel.textAlignment = NSTextAlignmentLeft;
    _speedLabel.textColor = [UIColor whiteColor];
    _speedLabel.font = SNFONTMIN(FitFont(16));
    [_bottomView addSubview:_speedLabel];
    
     UILabel *timeT = [[UILabel alloc]initWithFrame:CGRectMake(HHHWIDTH*3/5, finishLabel.bottom, HHHWIDTH/5, FitH(30))];
    timeT.textAlignment = NSTextAlignmentRight;
    timeT.textColor = [UIColor whiteColor];
    timeT.text = SN_Text(@"已耗时");
    timeT.font = SNFONT(FitFont(16));
    [_bottomView addSubview:timeT];
    CGSize sizeT = [self returnTrueSizeOfLabel:timeT];
    timeT.frame = CGRectMake(HHHWIDTH*3/4-sizeT.width-2+10, finishLabel.bottom, sizeT.width, sizeT.height);
    
    _timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(timeT.right + 5,finishLabel.bottom, HHHWIDTH*1/5, FitH(30))];
    _timeLabel.text = @"";
    _timeLabel.textAlignment = NSTextAlignmentLeft;
    _timeLabel.textColor = [UIColor whiteColor];
    _timeLabel.font = SNFONTMIN(FitFont(16));
    [_bottomView addSubview:_timeLabel];
    
    
    UILabel *paceT = [[UILabel alloc]initWithFrame:CGRectMake(5, _speedLabel.bottom, HHHWIDTH/6-5, FitH(30))];
    paceT.textAlignment = NSTextAlignmentLeft;
    paceT.textColor = [UIColor whiteColor];
    paceT.text = SN_Text(@"配速");
    paceT.font = SNFONT(FitFont(16));
    [_bottomView addSubview:paceT];
    paceT.size = [self returnTrueSizeOfLabel:paceT];
    
    _paceLabel = [[UILabel alloc]initWithFrame:CGRectMake(paceT.right+5,speedT.bottom, HHHWIDTH/4-10, FitH(30))];
    _paceLabel.text = @"";
    _paceLabel.textAlignment = NSTextAlignmentLeft;
    _paceLabel.textColor = [UIColor whiteColor];
    _paceLabel.font = SNFONTMIN(FitFont(16));
    [_bottomView addSubview:_paceLabel];
   
}
-(void)backBtnClick:(UIButton *)sender{
    if(_startBtn.hidden==YES){
        [_mapView setRegion:_region animated:true];
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:SN_Text(@"是否确定？") message:SN_Text(@"退出并且保存当前运动轨迹与数据，如果运动时长过短则不会保存数据，是否要继续？") delegate:self cancelButtonTitle:SN_Text(@"取消") otherButtonTitles:SN_Text(@"确定"), nil];
        [[UIView appearance] setTintColor:UIColorRGB(72, 72, 72)];
        [alert show];
        [self.localManager stopUpdatingLocation];
    }else{
        [self.localManager stopUpdatingLocation];
        if (self.BackBtnClickBlock) {
            self.BackBtnClickBlock(sender);
        }
    }
}
- (void)snapshotScreenInView:(MKMapView *)contentView {
    CGSize size = contentView.bounds.size;
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    CGRect rect = contentView.frame;

    [contentView drawViewHierarchyInRect:rect afterScreenUpdates:YES];
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    CGFloat width = image.size.width*image.scale;
    CGFloat height = image.size.height*image.scale;
    CGRect rect1 = CGRectMake(0 ,(height-width)/2,width,width);
    UIImage * imgeee = [UIImage imageWithCGImage:CGImageCreateWithImageInRect(image.CGImage, rect1)];
    _image = imgeee;
    NSString *path_document = NSHomeDirectory();
    //设置一个图片的存储路径
    NSString *imageName =[NSString stringWithFormat:@"/Documents/%f.png",[NSDate date].timeIntervalSince1970];
    NSString *imagePath = [path_document stringByAppendingString:imageName];
    //把图片直接保存到指定的路径（同时应该把图片的路径imagePath存起来，下次就可以直接用来取）
    [UIImagePNGRepresentation(imgeee) writeToFile:imagePath atomically:YES];
    _trackModel.imagePath = imageName;
}


- (void)saveMap
{
    [_timer invalidate];
    _timer = nil;
    _trackModel.totalDistances = _distance;
    _trackModel.sportTotalTime =_totalTime;
    _trackModel.averageSpeed = _trackModel.totalDistances/_trackModel.sportTotalTime;
    _trackModel.maxSpeed = [[_speedArr valueForKeyPath:@"@max.floatValue"] floatValue];
    _trackModel.averagePace =_distance==0?0:(_totalTime*1000/_distance);
    [self snapshotScreenInView:_mapView];
    [self.geocoder reverseGeocodeLocation:_annoArr.lastObject completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        CLPlacemark *pl = [placemarks firstObject];
        _trackModel.address = [NSString stringWithFormat:@"%@-%@-%@",pl.addressDictionary[@"State"],pl.addressDictionary[@"City"],pl.addressDictionary[@"SubLocality"]];
        _trackModel.trackArray = [NSArray arrayWithArray:_allDataArray];
        [_trackModel saveToDB];
        NSDictionary *dict = @{@"access_token":SN_USER.access_token,
                               @"user_id":SN_USER.user_id,
                               @"date":_trackModel.startTime,
                               @"distance":[NSString stringWithFormat:@"%ld",(long)_trackModel.totalDistances],
                               @"duration":@(_trackModel.sportTotalTime),
                               @"average_speed":[NSString stringWithFormat:@"%.2f",_trackModel.averageSpeed],
                               @"average_pace":@(_trackModel.averagePace),
                               @"fast_speed":[NSString stringWithFormat:@"%.2f",_trackModel.maxSpeed],
                               @"location":_trackModel.address,
                               @"cal":@(_trackModel.calorss),@"data":[_allDataArray YYJSONString]
                               };
        SHOWMBProgressHUDIndeterminate(nil, nil, @"登录中");
        [SN_Net uploadDataToServer:@"/sport/uploadtrack" dict:dict image:_image imageName:_trackModel.imagePath success:^(id object) {
            HIDDENMBProgressHUD;
            SHOWMBProgressHUD(nil, SN_Text(object[@"message"]), nil, NO, 2);
            if (object[@"ret"] && [object[@"ret"] intValue] == 0){
                if (self.BackBtnClickBlock) {
                    self.BackBtnClickBlock(_backBtn);
                }
            }
        } fail:^(id object) {
            HIDDENMBProgressHUD;
            SHOWMBProgressHUD(nil, SN_Text([object localizedDescription]), nil, NO, 2);
        }];
    }];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex==1){
        if (_distance>=50) {
            [self saveMap];
//            [SN_Net checkNetSuccess:^(id object) {
//                NSLog(@"网络状态>>>%@",object);
//                if ([object isEqualToString:@"1"]) {
//                    [self saveMap];
//                }
//                else
//                {
//                    SHOWMBProgressHUD(SN_Text(@"网络异常"), nil, nil, NO, 2.0);
//                }
//            }];
       }
    }else{
        [self.localManager startUpdatingLocation];
    }
}
-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex==1 && _distance<50) {
        SHOWMBProgressHUD(nil, SN_Text(@"本次运动距离小于50米，数据不做保留"), nil, NO, 2.0);
        if (self.BackBtnClickBlock) {
            self.BackBtnClickBlock(_backBtn);
        }
    }
}
-(void)setBtnClick:(UIButton *)sender{
    [self.localManager stopUpdatingLocation];
    if (self.SetBtnClickBlock) {
        self.SetBtnClickBlock(sender);
    }
}
-(void)shareBtnClick:(UIButton *)sender{
    [self.localManager stopUpdatingLocation];
    if (self.ShareBtnClickBlock) {
        self.ShareBtnClickBlock(sender);
    }
}
-(void)locationBtnClick:(UIButton *)sender{
    CLLocationCoordinate2D coord = ((CLLocation *)_annoArr.lastObject).coordinate;
    if (![LocationTranformTool isLocationOutOfChina:coord]) {
        coord = [LocationTranformTool transformFromWGSToGCJ:coord];
        
    }
    MKCoordinateSpan span = MKCoordinateSpanMake(0.001, 0.001);
    MKCoordinateRegion region=MKCoordinateRegionMake(coord, span);
    [_mapView setRegion:region animated:true];
}
-(void)startBtnClick:(UIButton *)sender{
    _startBtn.hidden = YES;
    _backView.hidden = YES;
    _locationBtn.hidden = NO;
    _bottomView.hidden = NO;
    [self.localManager startUpdatingLocation];
    _trackModel.startTime = [[NSDate date] dateToString];
    [self performSelector:@selector(addTimer) withObject:nil afterDelay:4];
    if (self.StartBtnClickBlock) {
        self.StartBtnClickBlock(sender);
    }
}
-(void)addTimer{
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(recordeTime) userInfo:nil repeats:YES];
}
-(void)recordeTime{
    _totalTime++;
    _timeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld:%02ld",_totalTime/3600,(_totalTime%3600)/60,_totalTime%60];
}
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:{
            NSLog(@"用户还未进行授权");
            break;
        }
        case kCLAuthorizationStatusDenied:{
            // 判断当前设备是否支持定位和定位服务是否开启
            if([CLLocationManager locationServicesEnabled]){
                
                NSLog(@"用户不允许程序访问位置信息或者手动关闭了位置信息的访问，帮助跳转到设置界面");
                
                NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                if ([[UIApplication sharedApplication] canOpenURL:url]) {
                    [[UIApplication sharedApplication] openURL: url];
                }
            }else{
                NSLog(@"定位服务关闭,弹出系统的提示框,点击设置可以跳转到定位服务界面进行定位服务的开启");
            }
            break;
        }
        case kCLAuthorizationStatusRestricted:{
            NSLog(@"受限制的");
            break;
        }
        case kCLAuthorizationStatusAuthorizedAlways:{
            NSLog(@"授权允许在前台和后台均可使用定位服务");
            break;
        }
        case kCLAuthorizationStatusAuthorizedWhenInUse:{
            NSLog(@"授权允许在前台可使用定位服务");
            break;
        }
        default:
            break;
    }
}
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    // 设备的当前位置
    CLLocation *userLocation = [locations lastObject];
    CLLocationCoordinate2D coord;
    [self gpsStrengthWithLocation:locations.lastObject];
    if (![LocationTranformTool isLocationOutOfChina:userLocation.coordinate]) {
        coord = [LocationTranformTool transformFromWGSToGCJ:userLocation.coordinate];
        
    }else{
        coord = userLocation.coordinate;
    }
    CGFloat speed =userLocation.speed>=0?userLocation.speed:0;
    [_speedArr addObject:@(speed)];
    // 时速
    _speedLabel.text = SN_USER.isMetricSystem?[NSString stringWithFormat:@"%.2fmile/h",speed*3600/1000*0.6213712]:[NSString stringWithFormat:@"%.2fkm/h",speed*3600/1000];
    if (speed==0) {
        _paceLabel.text = @"00'00";
    }else{
        NSInteger pace = 1000/speed;
        // 配速
        _paceLabel.text = [NSString stringWithFormat:@"%02ld'%02ld",pace/60,pace%60];
    }
    if (_locationMutableArray.count != 0 && _startBtn.hidden==YES) {
        //从位置数组中取出最新的位置数据
        NSString *locationStr = _locationMutableArray.lastObject;
        NSArray *temp = [locationStr componentsSeparatedByString:@","];
        NSString *latitudeStr = temp[0];
        NSString *longitudeStr = temp[1];
        CLLocationCoordinate2D startCoordinate = CLLocationCoordinate2DMake([latitudeStr doubleValue], [longitudeStr doubleValue]);
        CLLocation *startLocation = _annoArr.lastObject;
        //当前确定到的位置数据
        CLLocationCoordinate2D endCoordinate;
        endCoordinate.latitude = coord.latitude;
        endCoordinate.longitude = coord.longitude;
        //移动距离的计算
        
        double meters = [self calculateDistanceWithStart:startCoordinate end:endCoordinate];
        //double meters = [userLocation distanceFromLocation:startLocation];
        NSLog(@"移动的距离为%f米",meters);
        if (meters>=20) {
            //为了美化移动的轨迹,移动的位置超过10米,方可添加进位置的数组
            _distance += meters;
            _distanceLabel.text = SN_USER.isMetricSystem?[NSString stringWithFormat:@"%.2fmile",_distance*0.0006214]:[NSString stringWithFormat:@"%.2fkm",_distance*1.0/1000];
            _calLabel.text = [NSString stringWithFormat:@"%.2fkcal",SN_USER.weight*_distance*1.0/1000*1.036];
            NSString *locationString = [NSString stringWithFormat:@"%.15f,%.15f",coord.latitude, coord.longitude];

            NSString *now1 = [[NSDate date]dateToDayString];
            NSString *now2 =  [[NSDate date]dateToTimeString];
            NSDictionary *dict = @{@"lat" : [NSString stringWithFormat:@"%.7f",coord.latitude], @"lon" : [NSString stringWithFormat:@"%.7f",coord.longitude],@"ele":[NSString stringWithFormat:@"%.1f",userLocation.altitude],@"time":[NSString stringWithFormat:@"%@ %@",now1,now2]};
            [_allDataArray addObject:dict];
            
            [_locationMutableArray addObject:locationString];
            [_annoArr addObject:userLocation];
            //开始绘制轨迹
            CLLocationCoordinate2D pointsToUse[2];
            pointsToUse[0] = startCoordinate;
            pointsToUse[1] = endCoordinate;
            //调用 addOverlay 方法后,会进入 rendererForOverlay 方法,完成轨迹的绘制
            MKPolyline *lineOne = [MKPolyline polylineWithCoordinates:pointsToUse count:2];
            [_mapView addOverlay:lineOne];
        }
        
    }else{
        //存放位置的数组,如果数组包含的对象个数为0,那么说明是第一次进入,将当前的位置添加到位置数组
        NSString *locationString = [NSString stringWithFormat:@"%.15f,%.15f",coord.latitude, coord.longitude];
        [_locationMutableArray addObject:locationString];
        [_annoArr addObject:userLocation];
        
        NSString *now1 = [[NSDate date]dateToDayString];
        NSString *now2 =  [[NSDate date]dateToTimeString];
        NSDictionary *dict = @{@"lat" : [NSString stringWithFormat:@"%.7f",coord.latitude], @"lon" : [NSString stringWithFormat:@"%.7f",coord.longitude],@"ele":[NSString stringWithFormat:@"%.1f",userLocation.altitude],@"time":[NSString stringWithFormat:@"%@ %@",now1,now2]};
        
        [_allDataArray addObject:dict];
    }
      [self getCenterAndRegion];
}

-(void)gpsStrengthWithLocation:(CLLocation *)location{
    
    if (location.horizontalAccuracy>70 ) {
        [_gpsImageView setImage:[UIImage imageWithColor:UIColorHEX(0xD3292D)]];
        [_signImageView setImage:UIImageNamed(@"信号4")];
    }
    if (location.horizontalAccuracy>45 &&location.horizontalAccuracy<=70) {
        [_gpsImageView setImage:[UIImage imageWithColor:UIColorHEX(0xF3D045)]];
        [_signImageView setImage:UIImageNamed(@"信号3")];
    }
    if (location.horizontalAccuracy>20 &&location.horizontalAccuracy<=45) {
        [_gpsImageView setImage:[UIImage imageWithColor:UIColorHEX(0x81C716)]];
        [_signImageView setImage:UIImageNamed(@"信号2")];
    }
    if (location.horizontalAccuracy<=20 ) {
       [_gpsImageView setImage:[UIImage imageWithColor:UIColorHEX(0x81C716)]];
        [_signImageView setImage:UIImageNamed(@"信号1")];
    }
    
}
//定位失败的回调方法
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"无法获取当前位置 error : %@",error.localizedDescription);
}

-(MKOverlayRenderer *)mapView:(MKMapView *)mapView rendererForOverlay:(id)overlay{
    
    if ([overlay isKindOfClass:[MKPolyline class]]){
#pragma clang diagnostic push
#pragma clang diagnostic ignored"-Wdeprecated-declarations"
        MKPolylineView *polyLineView = [[MKPolylineView alloc] initWithPolyline:overlay];
        polyLineView.lineWidth = 5; //折线宽度
        polyLineView.strokeColor = UIColorHEX(0x00DB95); //折线颜色
        return (MKOverlayRenderer *)polyLineView;
#pragma clang diagnostic pop
    }else{
        return nil;
    }
    
}
#pragma mark - 距离测算
- (double)calculateDistanceWithStart:(CLLocationCoordinate2D)start end:(CLLocationCoordinate2D)end {
    
    double meter = 0;
    
    double startLongitude = start.longitude;
    double startLatitude = start.latitude;
    double endLongitude = end.longitude;
    double endLatitude = end.latitude;
    
    double radLatitude1 = startLatitude * M_PI / 180.0;
    double radLatitude2 = endLatitude * M_PI / 180.0;
    double a = fabs(radLatitude1 - radLatitude2);
    double b = fabs(startLongitude * M_PI / 180.0 - endLongitude * M_PI / 180.0);
    
    double s = 2 * asin(sqrt(pow(sin(a/2),2) + cos(radLatitude1) * cos(radLatitude2) * pow(sin(b/2),2)));
    s = s * 6378137;
    
    meter = round(s * 10000) / 10000;
    return meter;
}

-(void)getCenterAndRegion{
    
    for (NSInteger i = 0; i < _annoArr.count; i++) {
        MKUserLocation *loction = _annoArr[i];
        CLLocationCoordinate2D coord;
        if (![LocationTranformTool isLocationOutOfChina:loction.coordinate]) {
            coord = [LocationTranformTool transformFromWGSToGCJ:loction.coordinate];
            
        }else{
            coord = loction.coordinate;
        }
        if (i==0) {
            //以第一个坐标点做初始值
            _minLat = coord.latitude;
            _maxLat = coord.latitude;
            _minLon = coord.longitude;
            _maxLon = coord.longitude;
            
        }else{
            //对比筛选出最小纬度，最大纬度；最小经度，最大经度
            _minLat = MIN(_minLat, coord.latitude);
            _maxLat = MAX(_maxLat, coord.latitude);
            _minLon = MIN(_minLon, coord.longitude);
            _maxLon = MAX(_maxLon, coord.longitude);
        }
        //动态的根据坐标数据的区域，来确定地图的显示中心点和缩放级别
        if (_annoArr.count > 0) {
            //计算中心点
            CLLocationCoordinate2D centCoor;
            centCoor.latitude = (CLLocationDegrees)((_maxLat+_minLat) * 0.5f);
            centCoor.longitude = (CLLocationDegrees)((_maxLon+_minLon) * 0.5f);
            MKCoordinateSpan span;
            //计算地理位置的跨度
            span.latitudeDelta = (_maxLat - _minLat)*2;
            span.longitudeDelta = (_maxLon - _minLon)*2;
            //得出数据的坐标区域
            _region = MKCoordinateRegionMake(centCoor, span);
        }
        
    }
    CLLocationCoordinate2D startCoord;
    CLLocationCoordinate2D endCoord;
    if (_annoArr.count>0) {
        _startAnno = [[HMAnnotation alloc]init];
        _startAnno.icon = @"开始-1";
        MKUserLocation *start = _annoArr.firstObject;
        if (![LocationTranformTool isLocationOutOfChina:start.coordinate]) {
            startCoord = [LocationTranformTool transformFromWGSToGCJ:start.coordinate];
            
        }else{
            startCoord = start.coordinate;
        }
        
        _startAnno.coordinate = startCoord;
        [_mapView addAnnotation:_startAnno];
    }
    if (_annoArr.count>1) {
        [_mapView removeAnnotation:_endAnno];
        _endAnno = [[HMAnnotation alloc]init];
        _endAnno.icon = @"终点";
        MKUserLocation *end = _annoArr.lastObject;
        if (![LocationTranformTool isLocationOutOfChina:end.coordinate]) {
            endCoord = [LocationTranformTool transformFromWGSToGCJ:end.coordinate];
            
        }else{
            endCoord = end.coordinate;
        }
        
        double meters = [self calculateDistanceWithStart:startCoord end:endCoord];
        if (meters > 20.0) {
            _endAnno.coordinate = endCoord;
            [_mapView addAnnotation:_endAnno];
        }
    }
    
     [_mapView setRegion:_region];
}
#pragma mark - MKMapViewDelegate
-(void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated{

    if (mapView.annotations.count==2) {
        
    }
}
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(HMAnnotation *)annotation
{
    // 返回nil就会按照系统的默认做法
    if (![annotation isKindOfClass:[HMAnnotation class]]) return nil;
    
    // 1.获得大头针控件
    HMAnnotationView *annoView = [HMAnnotationView annotationViewWithMapView:mapView];
    
    // 2.传递模型
    annoView.annotation = annotation;
    
    return annoView;
}
-(CGSize)returnTrueSizeOfLabel:(UILabel *)label{
    CGSize titleSize = [label.text sizeWithFont:label.font maxSize:CGSizeMake(MAXFLOAT, FitH(30))];
    label.size = CGSizeMake(titleSize.width, FitH(30));
    return label.size;
}
@end
